package cn.com.jinhao.hotline.gateway.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * hotline-spring-cloud
 * <p>Description: </p>
 *
 * @author ShaneMew
 * @version 1.0
 * @date 2020/1/9
 * @since 2020-01-09
 */

@Component
public class RedisService {
    @Value("${redis.expire.time}")
    private Long expireTime;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 添加redis信息
     *
     * @param key
     */
    public void setString(String key, String value) {
        set(key, value);
    }

    //传入object对象
    private void set(String key, Object value) {
        if (value != null) {
            if (value instanceof String) {
                String setValue = (String) value;
                stringRedisTemplate.opsForValue().set(key, setValue);
            }
            //设置有效期
            if (expireTime != null) {
                stringRedisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            }
        }
    }

    /**
     *
     */
    public void updateExpireTime(String key) {
        stringRedisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
    }

    /**
     * 使用key查找redis信息
     *
     * @param key
     */
    public String get(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 使用key删除redis信息
     *
     * @param key
     */
    public void delete(String key) {
        stringRedisTemplate.delete(key);
    }
}
